<!--
 * @Author: wjk
 * @Date: 2019-12-31 15:40:51
 * @LastEditors: wangzm
 * @LastEditTime: 2020-03-07 14:34:57
 * @description: file content
 -->
<template>
  <base-page-view :class-name="'search-container '">
    <view class="sticky-wrap">
      <view class="search-block">
        <view class="search-left">
          <search-bar ref="search-bar" :keyword="listQuery.keyword" :placeholder="placeholderText" background="#F5F5F6" @clear="keyClear" @change="keyChange" @search="searchAction"></search-bar>
        </view>
        <view class="back-btn" @click="backClick">取消</view>
      </view>
      <!--<sort-bar v-if="showResult" :sort.sync="sortQuery" @change="handleSortChange" />-->
    </view>

    <template v-if="listQuery.keyword">
      <!-- 搜索结果 -->
      <card-box v-if="orderListData.length" :order-list="orderListData" :params="params" @showCodePopup="showCodePopup"></card-box>
      <view v-if="showResult" class="goods-list" :class="goodsLayout">
        <view v-for="(item, index) in list" :key="index" class="goods-item-container">
          <goods-item class-name="goods-item" :goods-data="item" :layout="goodsLayout" :goods-status="goodsLayout==='vertical'?-1:6" :image-width="goodsLayout==='vertical'?'100%':'260rpx'" image-radius="0" @click="itemClick($event, index)"></goods-item>
        </view>
        <base-list-state class="noResult" :list-length="listLength" :list-query="{page_no: listQuery.page_no, page_size: listQuery.page_size}" :list-state="listQuery" :list-empty="listEmpty" />
        <view v-show="!orderListData.length && !listQuery.loading" class="moreProduct">
          <view class="decotate">
            <text class="decorete_text">猜您喜欢</text>
            <text class="sub">ALL THE GOODS</text>
          </view>
          <likeList image-radius="0" :show-sub-name="showSub" />
        </view>
      </view>
      <!-- 搜索关联关键字-->
      <view v-else-if="keyword.suggest.length" class="keyword-suggest-list">
        <view v-for="(item, index) in keyword.suggest" :key="index" class="keyword-item" @click="keywordClick(item, 'suggest')">
          <span v-for="(sItem, sIndex) in item.split('')" :key="sIndex" :class="{'fontBold': listQuery.searchKey.indexOf(sItem) > -1}">{{ item[sIndex] }}</span>
        </view>
      </view>
    </template>
    <view v-else class="history-list">
      <!-- 搜索历史 -->
      <view v-if="keyword.history.length" class="keyword-block history">
        <view class="block-title">
          <view class="sub-item">最近搜索</view>
          <image class="icon" src="/static/images/icon/icon_delete.png" mode="aspectFit" @click="clearHistory" />
        </view>
        <view class="block-content">
          <template v-for="(item, index) in keyword.history">
            <view v-if="item" :key="index" class="keyword-item" @click="keywordClick(item)">
              {{ item }}
              <image class="right_arror" src="/static/images/icon/icon_arror_right.png" />
            </view>
          </template>

        </view>
      </view>
    </view>
    <!-- 验证码弹窗 -->
    <codePopup ref="codePopup" @again="sendCode" @success="code=>checkCode(code)"/>
    <!-- 交易密码弹窗 -->
    <dealPassword ref="dealPassword" v-if="showDealPassword" @complete="completePassword" @close="closeDealPassword"></dealPassword>  
  </base-page-view>
</template>

<script>
import searchBar from '@/components/searchBar/index'
// import sortBar from '@/components/sortBar/index'
// import goodsItem from '@/components/goodsItem/index.vue'
import { debounce } from '@/utils/tools'
import cardBox from '../order/cardBox'
import { mapGetters } from 'vuex'
import likeList from '@/components/likeGoodsList/index'
import codePopup from '@/components/popup/codePopup'
import dealPassword from '@/components/pay/dealPassword'
import './index.scss'
export default {
  components: {
    searchBar,
    likeList,
    // goodsItem,
    cardBox,
    codePopup,
    dealPassword
  },
  data() {
    return {
      showSub: false,
      from: 'normal', // normal: 我的订单、box: 箱起我的提货订单
      placeholderText: '搜索收件人\\收件人电话',
      keyType: '', // 埋点用, history、hot、suggest
      keyword: {
        history: [],
        hot: [],
        suggest: []
      },
      params: {
        orderStatusVal: ''
      },
      orderListData: [],
      sortQuery: {
        all: 1,
        sale: null,
        news: null,
        price: null
      },
      refreshFlag: false,
      goodsLayout: 'horizontal',
      listQuery: {
        // keyword: '',
        // sort: 'DESC',
        // sortField: 'COMPOSITE',
        // pageNo: 1,
        // pageSize: 10,
        userId: '',
        status: '',
        keyword: '',
        page_no: 1,
        page_size: 10,
        loading: false,
        more: true
      },
      list: [],
      listState: {
        loading: false,
        more: true
      },
      listEmpty: { type: 'empty__order', text: '亲，您没有相关的订单哦～' },
      showResult: false,
      showDealPassword: false,   // 交易密码弹窗
    }
  },
  computed: {
    ...mapGetters(['user']),
    listLength() { // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.orderListData.length
    }
  },
  onLoad(option) {
    this.from = option.from || 'normal'
    this.listQuery = {
      userId: this.user.uid,
      status: '',
      keyword: '',
      box_order_type: this.from === 'box' ? 2 : '',
      page_no: 1,
      page_size: 10,
      loading: false,
      more: true
    }
    this.list = []
    this.getHistory()
  },
  onReachBottom: debounce(function() {
    if (this.listQuery.more && !this.listQuery.loading) {
      this.listQuery.page_no++
      this.listQuery.loading = true
      this.$api.orderApi.getOrderList(this.listQuery).then(res => {
        this.listQuery.loading = false
        const arr = res.data
        if (!arr.length) { return }
        if (this.orderListData.length >= 10) {
          this.listQuery.more = true
        } else {
          this.listQuery.more = false
        }
        arr.map(item => {
          this.orderListData.push(item)
        })
      })
    }
  }, 500),
  methods: {
    //显示验证码弹窗
    showCodePopup(item){
      this.payOrderNo=item.order_no;
      this.showDealPassword = true
      // this.$refs.codePopup.show();
      this.sendCode();//发送验证码
    },
    async getPublicKey() {
      let res = await this.$api.mineApi.tradePasswordGetPublicKey()
      if (res.code === 0) {
        this.publicKey = res.data
      }
    },
    // 交易密码输入完成
    async completePassword(str){
      await this.getPublicKey()
       // 加密, 提交
      let jse = new this.$jsEncrypt()
      jse.setPublicKey(this.publicKey)
      let encrypted = jse.encrypt(str)
      this.checkCode(encrypted)
    },
    //发送验证码
    sendCode(){
      this.$api.orderApi.orderPay({
        pay_channel:11, // pay_channel为9时发送验证码,
        order_no: this.payOrderNo
      }).then(res=>{
        if(res.code==0){
          // this.$msg("验证码发送成功");
          // this.$refs.codePopup.countDown();//验证码倒计时
        }
      })
    },
    //判断验证码是否正确
    checkCode(password){
      this.$api.orderApi.checkVerifyDealPassword({
        password: password, 
        order_no: this.payOrderNo
      }).then(res=>{
        this.showDealPassword = false
        // this.$refs.codePopup.close();//关闭验证码弹窗
        this.$navigateTo('/pagesOrder/orderSuccess/index?orderNo=' + this.payOrderNo)
      }).catch((err)=>{
        // 1000002
        if(err.code === 1000002){
          this.showDealPassword = false
          uni.showToast({
            title: "未设置密码，请先设置",
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            this.$navigateTo("/pagesMine/dealPassword/index")
          }, 2000);
        }else{
          // 清除密码
          this.$refs.dealPassword.clearPassword()
          uni.showToast({
            title: err.msg,
            icon: 'none',
            duration: 3 * 1000
          })
        }
      });
    },
    // 获取历史搜索记录
    async getHistory() {
      const res = await this.$api.orderApi.getSearchHistory({ userId: this.user.uid })
      this.keyword.history = res.data || []
    },
    async fetchSuggestData() {
      this.keyword.suggest = []
      this.showResult = false
      const res = await this.$api.homeApi.searchSuggest({ searchKey: this.listQuery.searchKey })
      if (res.success) {
        this.keyword.suggest = res.data || []
      }
    },
    clearHistory() {
      this.$api.orderApi.searchHistoryClear({ userId: this.user.uid,
        hideLoading: true }).then(res => {
        this.keyword.history = []
      })
      // this.$gc.$message({
      //   content: '确认清空历史记录?',
      //   title: '提示',
      //   confirmColor: '#FFF', // 确认按钮颜色,
      //   confirmBackground: '#FF759F', // 确认按钮背景色
      //   confirmText: '确定',
      //   align: 'center',
      //   confirm: () => {
      //
      //   }
      // })
    },
    keyChange(value) {
      this.listQuery.keyword = value
      this.fetchSuggestData()
    },
    keyClear() {
      this.listQuery.keyword = ''
      this.showResult = false
      this.getHistory()
    },
    keywordClick(value) {
      this.listQuery.keyword = value
      this.$refs['search-bar'].setValue(value)
      this.searchAction(value)
    },
    async searchAction(type) {
      // const data = {
      //   userId: this.user.uid,
      //   status: '',
      //   search: type,
      //   page_no: 1,
      //   page_size: 10
      // }
      this.listQuery.loading = true
      this.showResult = true
      this.listQuery.page_no = 1
      this.listQuery.keyword = type
      const res = await this.$api.orderApi.getOrderList(this.listQuery)
      this.listQuery.loading = false
      this.orderListData = res.data
      if (this.orderListData.length >= 10) {
        this.listQuery.more = true
      } else {
        this.listQuery.more = false
      }
    },
    itemClick(item, index) {
      this.$sensorTrack('SEARCH_RESULT', {
        page_name: 'search',
        key_word: this.listQuery.searchKey,
        content_name: item.title,
        commodity_id: item.goods_id
      })
    },
    backClick() {
      uni.navigateBack()
    }
  }
}
</script>
